<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2007/02/13 06:47:44 $)
// $RCSfile: functions_escalations.php,v $ : $Revision: 1.12 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Runs escalation rules on pending tickets
*/
function runEscalationRules()
{
	global $dbCore, $_SWIFT;

	$slaplanidlist = $ticketidlist = $escalationpointer = $_ticketpointer = array();

//	print_r($_SWIFT["escalationrulecache"]);
	if (!count($_SWIFT["escalationrulecache"]))
	{
		return false;
	}

	// First build a list of sla plan ids
	foreach ($_SWIFT["escalationrulecache"] as $key=>$val)
	{
		$slaplanidlist[] = $val["slaplanid"];
		$escalationpointer[$val["slaplanid"]] = $val;
	}

	if (!count($slaplanidlist))
	{
		return false;
	}

	// Build the Status List
	$_slaticketstatusidlist = array();
	foreach ($slaplanidlist as $key=>$val)
	{
		$_slaplan = $_SWIFT["slaplancache"][$val];

		foreach ($_slaplan["ticketstatuslink"] as $statuskey=>$statusval)
		{
			if (!in_array($statusval, $_slaticketstatusidlist))
			{
				$_slaticketstatusidlist[] = $statusval;
			}
		}
	}

	print_r($slaplanidlist);
	print_r($_slaticketstatusidlist);

	$dbCore->query("SELECT `ticketid`, `slaplanid`, `isescalated`, `ticketstatusid` FROM `". TABLE_PREFIX ."tickets` WHERE (`slaplanid` IN (". buildIN($slaplanidlist) .") OR `ticketslaplanid` IN (". buildIN($slaplanidlist) .")) AND (`duetime` <= '". DATENOW ."' AND `duetime` != 0) AND `ticketstatusid` IN (". buildIN($_slaticketstatusidlist) .");");
	while ($dbCore->nextRecord())
	{
		$_slaplan = $_SWIFT["slaplancache"][$dbCore->Record["slaplanid"]];
		if (in_array($dbCore->Record["ticketstatusid"], $_slaplan["ticketstatuslink"]))
		{
			$ticketidlist[$dbCore->Record["slaplanid"]][] = $dbCore->Record["ticketid"];
			$_ticketpointer[$dbCore->Record["ticketid"]] = $dbCore->Record;
		}
	}

//	print_r($_ticketpointer);

	if (!count($ticketidlist))
	{
		echo "No Tickets Found".SWIFT_CRLF;
		return false;
	}


	foreach ($ticketidlist as $key=>$val)
	{
		$ownerstaffid = $departmentid = $ticketstatusid = $priorityid = false;
		$_escalationrule = $escalationpointer[$key];

		if (!empty($_escalationrule["staffid"]))
		{
			$ownerstaffid = intval($_escalationrule["staffid"]);
		}

		if (!empty($_escalationrule["departmentid"]))
		{
			$departmentid = intval($_escalationrule["departmentid"]);
		}

		if (!empty($_escalationrule["ticketstatusid"]))
		{
			$ticketstatusid = intval($_escalationrule["ticketstatusid"]);
		}

		if (!empty($_escalationrule["priorityid"]))
		{
			$priorityid = intval($_escalationrule["priorityid"]);
		}

		$_finalticketidlist = array();
		foreach ($val as $ticketkey=>$ticketval)
		{
			echo "Escalating Ticket: ".$ticketval."<BR />";
//			if ($_ticketpointer[$ticketval]["slaplanid"] == $_escalationrule["slaplanid"] && $_ticketpointer[$ticketval]["isescalated"] == "1")
//			{
//				echo "Ticket was executed under the same SLA Plan before, moving to next ticket<BR />";
//				continue;
//			} else {
				echo "Escalating: ".$ticketval."\n<br>";
				$_finalticketidlist[] = $ticketval;
//			}
		}

		// Run the escalation rule
		if (count($_finalticketidlist) && ($ownerstaffid || $departmentid || $ticketstatusid || $priorityid))
		{
			updateTicketStatus($_finalticketidlist, false, $ownerstaffid, $departmentid, $ticketstatusid, $priorityid, "-1", $_escalationrule["escalationruleid"]);
		}
	}

	return true;
}

/**
* Insert a New Escalation Rule
*/
function insertEscalationRule($title, $slaplanid, $staffid, $priorityid, $ticketstatusid, $departmentid)
{
	global $dbCore, $_SWIFT;

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."escalationrules` (`slaplanid`, `staffid`, `priorityid`, `ticketstatusid`, `departmentid`, `title`, `dateline`) VALUES ('". intval($slaplanid) ."', '". intval($staffid) ."', '". intval($priorityid) ."', '". intval($ticketstatusid) ."', '". intval($departmentid) ."', '". $dbCore->escape($title) ."', '". DATENOW ."');");

	$escalationruleid = $dbCore->lastInsertId();
	if (!$escalationruleid)
	{
		return false;
	}

	rebuildEscalationRuleCache();

	return $escalationruleid;
}

/**
* Update an Existing Escalation Rule
*/
function updateEscalationRule($escalationruleid, $title, $slaplanid, $staffid, $priorityid, $ticketstatusid, $departmentid)
{
	global $dbCore, $_SWIFT;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."escalationrules` SET `slaplanid` = '". intval($slaplanid) ."', staffid = '". intval($staffid) ."', priorityid = '". intval($priorityid) ."', ticketstatusid = '". intval($ticketstatusid) ."', departmentid = '". intval($departmentid) ."', title = '". $dbCore->escape($title) ."', dateline = '". DATENOW ."' WHERE `escalationruleid` = '". intval($escalationruleid) ."';");

	rebuildEscalationRuleCache();

	return true;
}

/**
* Delete the given Escalation Rules
*/
function deleteEscalationRules($escalationruleidlist)
{
	global $dbCore;
	
	if (!_is_array($escalationruleidlist))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."escalationrules` WHERE `escalationruleid` IN (". buildIN($escalationruleidlist) .");");

	rebuildEscalationRuleCache();

	return true;
}

/**
* Updates the Escalation Rule Cache
*/
function rebuildEscalationRuleCache()
{
	global $dbCore, $datastore;

	$escalationrulecache = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."escalationrules`;");
	while ($dbCore->nextRecord())
	{
		$escalationrulecache[$dbCore->Record["escalationruleid"]] = $dbCore->Record;
	}

	$datastore->update("escalationrulecache", $escalationrulecache);
}

/**
* Render the Escalation Rule form for Edit/Insert
*/
function renderEscalationForm($type)
{
	global $dbCore, $_SWIFT;

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["escalationruledetails"]);

	printTextRow("title", $_SWIFT["language"]["ruletitle"], $_SWIFT["language"]["desc_ruletitle"], "text", $_POST["title"]);

	// ======= RENDER SLA PLANS =======
	$index = 0;
	$dbCore->query("SELECT `slaplanid`, `title` FROM `". TABLE_PREFIX ."slaplans` ORDER BY `title` ASC;");
	while ($dbCore->nextRecord())
	{
		$options[$index]["title"] = $dbCore->Record["title"];
		$options[$index]["value"] = $dbCore->Record["slaplanid"];
		$index++;
	}
	if (!count($options))
	{
		$options[$index]["title"] = $_SWIFT["language"]["noplanavailable"];
		$options[$index]["value"] = "";
		$errormessage = iif($errormessage=="", $_SWIFT["language"]["errorinsertrule"], $errormessage);
	}
	printSelectRow("slaplanid", $_SWIFT["language"]["escalationplan"], $_SWIFT["language"]["desc_escalationplan"], $options);

	printDescRow($_SWIFT["language"]["escalationaction"]);

	// ======= RENDER STAFF LIST =======
	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["nochange"];
	$options[0]["value"] = "0";
	$index = 1;
	$dbCore->query("SELECT `staffid`, `fullname` FROM `". TABLE_PREFIX ."staff` ORDER BY `fullname` ASC;");
	while ($dbCore->nextRecord())
	{
		$options[$index]["title"] = $dbCore->Record["fullname"];
		$options[$index]["value"] = $dbCore->Record["staffid"];
		$index++;
	}
	printSelectRow("staffid", $_SWIFT["language"]["escalationstaff"], $_SWIFT["language"]["desc_escalationstaff"], $options);

	// ======= RENDER DEPARTMENT LIST =======
	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["nochange"];
	$options[0]["value"] = "0";
	$index = 1;
	$dbCore->query("SELECT `departmentid`, `title` FROM `". TABLE_PREFIX ."departments` WHERE `departmentmodule` = '". MODULE_TICKETS ."' ORDER BY `title` ASC;");
	while ($dbCore->nextRecord())
	{
		$options[$index]["title"] = $dbCore->Record["title"];
		$options[$index]["value"] = $dbCore->Record["departmentid"];
		$index++;
	}
	printSelectRow("departmentid", $_SWIFT["language"]["escalationdepartment"], $_SWIFT["language"]["desc_escalationdepartment"], $options);

	// ======= RENDER PRIORITY LIST =======
	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["nochange"];
	$options[0]["value"] = "0";
	$index = 1;
	$dbCore->query("SELECT `priorityid`, `title` FROM `". TABLE_PREFIX ."ticketpriorities` ORDER BY `title` ASC;");
	while ($dbCore->nextRecord())
	{
		$options[$index]["title"] = $dbCore->Record["title"];
		$options[$index]["value"] = $dbCore->Record["priorityid"];
		$index++;
	}
	printSelectRow("priorityid", $_SWIFT["language"]["escalationpriority"], $_SWIFT["language"]["desc_escalationpriority"], $options);

	// ======= RENDER TICKET STATUS LIST =======
	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["nochange"];
	$options[0]["value"] = "0";
	$index = 1;
	$dbCore->query("SELECT `ticketstatusid`, `title` FROM `". TABLE_PREFIX ."ticketstatus` ORDER BY `title` ASC;");
	while ($dbCore->nextRecord())
	{
		$options[$index]["title"] = $dbCore->Record["title"];
		$options[$index]["value"] = $dbCore->Record["ticketstatusid"];
		$index++;
	}
	printSelectRow("ticketstatusid", $_SWIFT["language"]["escalationticketstatus"], $_SWIFT["language"]["desc_escalationticketstatus"], $options);

	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insertrule"], $_SWIFT["language"]["updaterule"]));

	printMainTableFooter();

	addHiddenField("_m", "tickets");
	addHiddenField("_a", iif($type==INSERT, "insertescalationrule", "editescalationrule"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("escalationruleid", $_POST["escalationruleid"]);
	}
	printFormEnd();
}
?>